package com.small.nacos.core.datasource;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.env.Environment;

import java.util.concurrent.TimeUnit;

public class DataSourcePoolProperties {

    /**
     * 默认连接超时时间
     */
    public static final long DEFAULT_CONNECTION_TIMEOUT = TimeUnit.SECONDS.toMillis(30L);

    /**
     * 默认验证超时时间
     */
    public static final long DEFAULT_VALIDATION_TIMEOUT = TimeUnit.SECONDS.toMillis(10L);

    /**
     * 连接池最大数
     */
    public static final int DEFAULT_MAX_POOL_SIZE = 20;

    /**
     * 最小空闲连接数
     */
    public static final int DEFAULT_MINIMUM_IDLE = 2;

    private final HikariDataSource dataSource;

    private DataSourcePoolProperties() {
        dataSource = new HikariDataSource();
        dataSource.setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);
        dataSource.setValidationTimeout(DEFAULT_VALIDATION_TIMEOUT);
        dataSource.setMaximumPoolSize(DEFAULT_MAX_POOL_SIZE);
        dataSource.setMinimumIdle(DEFAULT_MINIMUM_IDLE);
    }

    /**
     * Build new Hikari config.
     *
     * @return new hikari config
     */
    public static DataSourcePoolProperties build(Environment environment) {
        DataSourcePoolProperties result = new DataSourcePoolProperties();
        Binder.get(environment).bind("db.pool.config", Bindable.ofInstance(result.getDataSource()));
        return result;
    }

    public void setDriverClassName(final String driverClassName) {
        dataSource.setDriverClassName(driverClassName);
    }

    public void setJdbcUrl(final String jdbcUrl) {
        dataSource.setJdbcUrl(jdbcUrl);
    }

    public void setUsername(final String username) {
        dataSource.setUsername(username);
    }

    public void setPassword(final String password) {
        dataSource.setPassword(password);
    }

    public HikariDataSource getDataSource() {
        return dataSource;
    }
}
